var warehouse = warehouse_list[0];
var client;
var map;
var autocomplete;
var direct;
var pathRender;

function initialize() {
    // options
    var mapOptions = {
        center: new google.maps.LatLng(50.44, 30.50),
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    var autocompleteOptions = {
        types: ['geocode']
    };

    // map objects
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    direct = new google.maps.DirectionsService();
    pathRender = new google.maps.DirectionsRenderer({ map: map });

    // autocomplete
    var search_field = document.getElementById('search');
    if (search_field) {
        autocomplete = new google.maps.places.Autocomplete(search_field, autocompleteOptions);
        autocomplete.bindTo('bounds', map);
        google.maps.event.addListener(autocomplete, 'place_changed', autocomplete_on_place_changed);
    }

    initUI();
}

function selectWHbyId(id) {
    $(':radio[value=' + id + ']').click();
}

function autocomplete_on_place_changed() {
    var place = autocomplete.getPlace();
    if (!place.geometry) {
        $('#result').hide();
        return;
    }
    client = place.geometry.location;
    $('input[name=destination]').val($('#search').val());
    findShortWay();
}

function destinationResult(result, status) {
    switch (status) {
        case google.maps.DirectionsStatus.OK:
            pathRender.setDirections(result);
            if (result.routes.length == 0)
                return;
            var info = result.routes[0].legs[0];
            $('#del_time').text(Math.round(info.distance.value / warehouse.duration_rate / 1000) + ' hours');
            $('#distance').text(Math.round(info.distance.value / 1000) + ' km');
            $('input[name=distance]').val(info.distance.value);
            $('#price').text(Math.round(info.distance.value * warehouse.cost_rate / 1000));
            $('#result').show();
            $('#error_path_not_found').hide();
            break;
        case google.maps.DirectionsStatus.ZERO_RESULTS:
            $('#del_time').text('');
            $('#distance').text('');
            $('input[name=distance]').val(0);
            $('#price').text(0);
            $('#result').hide();
            $('#error_path_not_found').show();
            break;
        default:
            //TODO: handle errors
            $('#result').hide();
            console.log('getDestination error', status);
    }
}

function findPath() {
    if (!client)
        return;
    getDestination(warehouse.position, client, destinationResult);
}

function initUI() {
    $('#result').hide();
    $('#error_path_not_found').hide();

    var wh_div = $('#wh_list');
    warehouse_list.forEach(function(wh, i) {
        wh_div.append(
            $('<input type="radio" name="wh_id" value="' + i + '">' + wh.name + ' - ' + wh.cost_rate + '$/mil<br>')
        );
    });

    $('input[name=wh_id]').click(function() {
        var wh = warehouse_list[$(this).attr('value')];
        if (!wh)
            return;
        warehouse = wh;
        $('#whAddress').text(wh.position);
        $('input[name=warehouse_id]').val(wh.id);
        findPath();
        if (!client && wh.point)
            map.setCenter(wh.point);
    });

    findShortWay(true);
}

function getDestination(from, to, cb) {
    var request = {
        destination: to,
        origin: from,
        provideRouteAlternatives: false,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL
    };
    direct.route(request, cb);
}

function findShortWay(find_markers) {
    var dest = $('input[name=destination]').val();
    var dest_fake = false;
    if (find_markers && !dest.length) {
        dest = warehouse_list[0].position;
        dest_fake = true;
    } else if (!dest) {
        return;
    }
    var distance = [];
    var end_position = [];
    var min = -1;
    warehouse_list.forEach(function(wh, i) {
        distance[i] = -1;
        end_position[i] = null;
        getDestination(wh.position, dest, function(result, status) {
            switch (status) {
                case google.maps.DirectionsStatus.OK:
                    if (result.routes.length == 0)
                        return;
                    var info = result.routes[0].legs[0];
                    if (!wh.point) {
                        var start = info.start_location;
                        wh.point = new google.maps.LatLng(start.hb, start.ib);
                        wh.marker = new google.maps.Marker({ position: wh.point, map: map });
                        google.maps.event.addListener(wh.marker, 'click', function() {
                            selectWHbyId(i);
                        });
                    }
                    if (!dest_fake) {
                        var end = info.end_location;
                        distance[i] = info.distance.value;
                        end_position[i] = new google.maps.LatLng(end.hb, end.ib);
                        if (min == -1 || distance[min] > distance[i])
                            min = i;
                    }
                   break;
                default:
                    distance[i] = 0;
                    console.log('Error status', status);
            }
            if (!dest_fake) {
                if (distance.length == warehouse_list.length) {
                    if (distance.every(function(i) { return i != -1; })) {
                        client = end_position[min];
                        selectWHbyId(min);
                        destinationResult(result, status);
                    }
                }
            } else {
                selectWHbyId(0);
            }
        });
    });
}

google.maps.event.addDomListener(window, 'load', initialize);
